package sql.tran.test;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;




public class BankOp {
	
	public static void main(String args[]){
		Connection con = null;
		Statement sql;
		ResultSet rs;
		try
		{
			
			Class.forName("com.mysql.jdbc.Driver");
		}catch(ClassNotFoundException e){
			System.out.println(""+e);
		}
		try{
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+"rual","root","rual");
			con.setAutoCommit(false);
			sql = con.createStatement();
			rs = sql.executeQuery("select * from bank where id = '1'");
			rs.next();
			int historymoney = rs.getInt("historymoney");
			System.out.println("事务操作之前historymoney为： "+historymoney);
			int currentmoney = rs.getInt("currentmoney");
			System.out.println("事务操作之前currentmoney为： "+currentmoney);
			historymoney = historymoney + 1000;
			currentmoney = currentmoney - 1000;
			sql.executeUpdate("update bank set historymoney = "+historymoney+" where id = '1'");
			sql.executeUpdate("update bank set currentmoney = "+currentmoney+" where id = '1'");
			con.commit();
			con.setAutoCommit(true);
			rs = sql.executeQuery("select * from bank where id = '1'");
			rs.next();
			historymoney = rs.getInt("historymoney");
			System.out.println("事务操作之后historymoney为： "+historymoney);
			currentmoney = rs.getInt("currentmoney");
			System.out.println("事务操作之后currentmoney为： "+currentmoney);
			con.close();
			
			
			
			
		}catch(SQLException e){
			try{
				con.rollback();
			}catch(SQLException exp){}
			System.out.println(e);
		}
		
	}

}
